﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SusuCMS.Web.Paging;
using System.Web.Routing;
using System.Web.Script.Serialization;

namespace SusuCMS.Web.Areas.Admin.Controllers
{

    public class PageTypeController : AdminControllerBase
    {
        #region Index
        public ActionResult Index()
        {
            var pageTypes = PageTypeRepository.FindAll().Where(i => i.WebsiteId == CurrentWebsiteId).ToList();
            var rootList = pageTypes.Where(i => i.Parent == null);

            var list = new List<PageType>();
            foreach (var item in rootList)
            {
                list.AddRange(BuildItem(item, pageTypes));
            }

            return View(list.AsQueryable());
        }

        IList<PageType> BuildItem(PageType pageType, IList<PageType> pageTypes)
        {
            var list = new List<PageType>();
            list.Add(pageType);
            var children = pageTypes.Where(i => i.ParentId == pageType.Id);
            foreach (var item in children)
            {
                list.AddRange(BuildItem(item, pageTypes));
            }

            return list;
        }
        #endregion

        #region Create

        public ActionResult Create()
        {
            return View(new PageType());
        }

        [HttpPost]
        public ActionResult Create(PageType model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    model.CreateTime = DateTime.Now;
                    model.WebsiteId = CurrentWebsiteId;

                    PageTypeRepository.Add(model);
                    UnitOfWork.Save();
                    TempData["Message"] = "Create PageType Successfully";

                    return RedirectToIndex();
                }
                catch
                {
                    TempData["ErrorMessage"] = "Create PageType Failed";
                }
            }

            return View(model);
        }

        #endregion

        #region Edit

        public ActionResult Edit(int id)
        {
            var page = PageTypeRepository.FindAll().FirstOrDefault(i => i.Id == id);
            if (page == null)
            {
                return HttpNotFound();
            }

            return View(page);
        }

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            var page = PageTypeRepository.FindAll().FirstOrDefault(i => i.Id == id);
            UpdateModel(page);

            try
            {
                UnitOfWork.Save();
                TempData["Message"] = "Edit PageType Successfully";

                return RedirectToIndex();
            }
            catch
            {
                TempData["ErrorMessage"] = "Edit Page Failed";
            }

            return View(page);
        }

        #endregion

        #region Delete
        [HttpPost]
        public ActionResult Delete(int id)
        {
            var page = PageTypeRepository.FindAll().FirstOrDefault(i => i.Id == id);
            if (page == null)
            {
                TempData["ErrorMessage"] = "PageType Not Exist";
            }

            try
            {
                PageTypeRepository.Remove(page);
                UnitOfWork.Save();
                TempData["Message"] = "Delete PageType Successfully";

                return RedirectToIndex();
            }
            catch
            {
                TempData["ErrorMessage"] = "Delete PageType Failed";
            }

            return RedirectToIndex();
        }

        #endregion

        #region Move
        [HttpPost]
        public ActionResult Move(int id, int? parentId)
        {
            var list = PageTypeRepository.FindAll().Where(i => i.WebsiteId == CurrentWebsiteId).ToList();
            var pageType = list.FirstOrDefault(i => i.Id == id);
            try
            {
                // check if the pageType to be moved is the parent of the pageType that move to.
                if (parentId != null)
                {
                    var parent = list.FirstOrDefault(i => i.Id == parentId.Value);
                    while (parent != null)
                    {
                        if (parent.Id == id)
                        {
                            TempData["ErrorMessage"] = "The Page Cann't Move Under It's Child";
                            return Redirect(Request.UrlReferrer.AbsoluteUri);
                        }
                        else
                        {
                            if (parent.ParentId.HasValue)
                            {
                                parent = list.FirstOrDefault(i => i.Id == parent.ParentId);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }

                pageType.ParentId = parentId;
                UnitOfWork.Save();
                TempData["Message"] = "Move PageType Successfully";
            }
            catch
            {
                TempData["ErrorMessage"] = "Move PageType Failed";
            }

            return Redirect(Request.UrlReferrer.AbsoluteUri);
        }
        #endregion

        #region ToggleOnline
        public ActionResult ToggleOnline(int id)
        {
            var pageType = PageTypeRepository.FindAll().FirstOrDefault(i => i.Id == id);
            if (pageType == null)
            {
                TempData["ErrorMessage"] = "PageType Not Exist";
            }
            else
            {
                try
                {
                    pageType.IsPublished = !pageType.IsPublished;
                    UnitOfWork.Save();
                    TempData["Message"] = "Toggle PageType Successfully";

                    return RedirectToIndex();
                }
                catch
                {
                    TempData["ErrorMessage"] = "Toggle PageType Failed";
                }
            }

            return RedirectToIndex();
        }

        #endregion

        [ChildActionOnly]
        public ActionResult List()
        {
            var list = PageTypeRepository.FindAll().Where(i => i.WebsiteId == CurrentWebsiteId).ToList();

            ViewBag.CurrentPageTypeId = CurrentPageTypeId;

            return PartialView(list);
        }

        public string IdentifierAvailable(string identifier, int id)
        {
            return (!PageTypeRepository.FindAll()
                .Where(i => i.WebsiteId == CurrentWebsiteId)
                .Any(i => i.Identifier.ToLower() == identifier.ToLower() && i.Id != id)).ToString().ToLower();
        }
    }
}
